package controllers

import (
	"context"
	"log"
	"t11Lib/t11Log"
	"t11Lib/t11Util"
	"time"
	"亚太-iot-服务器/biz"
	"亚太-iot-服务器/biz/wsBroker"
	"亚太-iot-服务器/conf"
	"亚太-iot-服务器/models"
)

// Operations about Users
type UserController struct {
	BaseController
}

//@router /GetWxUserIdForGatewayBind [post]
func (self *UserController) GetWxUserIdForGatewayBind() {
	wxUser, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	uid := t11Util.RandMd5()
	biz.UserIdCache.CacheUserId(wxUser, uid)
	self.RetJson(map[string]interface{}{
		"userId": uid,
		"note":   "有效时间为30分钟，每次绑定前需要重新获取",
	}, nil)
}

//@router /getTime [post]
func (self *UserController) GetTime() {
	name := self.GetString("name")
	t11Log.Debuglnf("name = %v", name)
	ret := make(map[string]interface{})
	ret["time"] = time.Now()
	ret["name"] = name
	self.RetOkJson(ret)
}

//@router /listGateways [post]
func (self *UserController) ListGateways() {
	wxUser, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	ret, err := biz.UserBiz.ListData(self.GetDbConn(), wxUser)
	self.RetJson(ret, err)
}

//@router /bindDevice [post]
func (self *UserController) BindDevice() {
	wxUser, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	dev := self.GetString("devId")
	//建立绑定关系
	self.RetStatusJson(biz.UserBiz.CreateDevAndUserDev(self.GetDbConn(), wxUser, dev))
}

//@router /DeleteGatewayForDevice [post]
func (self *UserController) DeleteGatewayForDevice() {
	wxUser, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	dev := self.GetString("devId")
	//建立绑定关系
	self.RetStatusJson(biz.UserBiz.DeleteGatewayForDevice(self.GetDbConn(), wxUser, dev))
}

//@router /CreateOrUpdateGurantee [post]
func (self *UserController) CreateOrUpdateGurantee() {
	wxUser, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	dev := self.GetString("devId")
	info := self.GetString("info")
	self.RetStatusJson(biz.UserBiz.CreateOrUpdateGuarantee(self.GetDbConn(), wxUser, dev, info))
}

//@router /deleteDevice [post]
func (self *UserController) DeleteDevice() {
	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	devId := self.GetString("devId")
	e := biz.UserBiz.DeleteDevice(self.GetDbConn(), devId, user)
	self.RetStatusJson(e)
}

//@router /setUserDeviceKv [post]
func (self *UserController) SetUserDeviceKv() {
	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	devId := self.GetString("devId")
	key := self.GetString("key")
	val := self.GetString("value")
	self.RetStatusJson(biz.UserBiz.SetDeviceKv(self.GetDbConn(), user, devId, key, val))
}

//@router /setUserGatewayKv [post]
func (self *UserController) SetUserGatewayKv() {
	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}
	gwId := self.GetString("gatewayId")
	key := self.GetString("key")
	val := self.GetString("value")
	self.RetStatusJson(biz.UserBiz.SetGatewayKv(self.GetDbConn(), user, gwId, key, val))
}

// @Title WsChannel
// @router /WsChannel [*]
func (c *UserController) WsChannel() {
	ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.TODO()
	conn := wsBroker.NewWsConnector(ws)
	go conn.WriteRoutine(ctx)
	go conn.ReadRoutine(ctx)
}

/**
请求设备的分享id
*/
//@router /GetWxShareIdForDeviceBind [get]
func (self *UserController) GetWxShareIdForDeviceBind() {

	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	shareId, _ := biz.DevShareDao.CreateShareId(user)
	self.RetJson(map[string]interface{}{
		"uid":  shareId,
		"note": "操作成功",
	}, nil)
}

/**
检测设备的绑定状态 [post请求]
参数1: shareId -- 通过接口 GetWxShareIdForDeviceBind 获取到的id
参数2: devId   -- 用户要绑定的设备id
参数3: userId  -- 调用该接口的wxUserId
返回值: Json格式的状态码
*/
//@router /BindWxShareDeviceCheck [post]
func (self *UserController) BindWxShareDeviceCheck() {

	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	shareId := self.GetString("shareId")
	devId := self.GetString("devId")

	errCode, err := biz.DevShareDao.BindShareDeviceCheck(user, shareId, devId)
	self.RetJson(map[string]interface{}{
		"note": errCode,
	}, nil)
}

/**
请求绑定分享设备 [post请求]
参数1: shareId -- 通过接口 GetWxShareIdForDeviceBind 获取到的id
参数2: devId   -- 用户要绑定的设备id
返回值: Json格式的状态码
*/
// @router /BindWxShareDevice [post]
func (self *UserController) BindWxShareDevice() {

	user, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	shareId := self.GetString("shareId")
	devId := self.GetString("devId")

	errCode, err := biz.DevShareDao.BindShareDevice(user, shareId, devId)
	self.RetJson(map[string]interface{}{
		"note": errCode,
	}, nil)
}

/**
获取共享设备列表 [get 请求]
参数1 : devId   --  该设备的机身码
返回值: Json 格式的设备列表
*/
// @router /ListShareDevice [get]
func (self *UserController) ListShareDevice() {

	token, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	dbConn := self.GetDbConn()
	devId := self.GetString("devId")

	devList, err := biz.UserBiz.ListShareDevices(dbConn, token, devId)
	self.RetJson(map[string]interface{}{
		"devList": devList,
	}, nil)
}

/**
删除共享设备 [get 请求]
参数1 : userId  --  使用 ListShareDevice 接口获取到的 userId
参数2 : devId   --  该设备的机身码
*/
// @router /DeleteWxShareDevice [get]
func (self *UserController) DeleteWxShareDevice() {

	errMsg := ""
	_, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	dbConn := self.GetDbConn()
	userId := self.GetString("userId")
	devId := self.GetString("devId")

	err = biz.DevShareDao.DeleteByUserId(dbConn, userId, devId)
	if err != nil {
		errMsg = "删除失败"
	} else {
		errMsg = "删除成功"
	}

	self.RetJson(map[string]interface{}{
		"note": errMsg,
	}, nil)
}

/**
判断设备是否已绑定
参数1: 需要判断的设备机身码
return Err_Ok or Err_DeviceHasBind
*/
// @router /CheckDeviceStatus [get]
func (self *UserController) CheckDeviceStatus() {

	var errCode int
	_, err := self.getWxUser()
	if err != nil {
		self.RetStatusJson(err)
		return
	}

	dbConn := self.GetDbConn()
	devId := self.GetString("devId")

	_, err = models.DeviceDao.GetById(dbConn, devId)
	if err != nil {
		errCode = conf.ErrOk
	} else {
		errCode = conf.ErrDeviceHasBind
	}

	self.RetErrJson(errCode)
}
